package com.pay.bean;

import com.pay.weixin.WxPayConfig;
import com.pay.weixin.util.PayCommonUtil;
import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

@Getter
@Setter
public abstract class WxResult implements Serializable {

    private Long originPayNotifyId;

    private String returnCode = "FAIL";  //"SUCCESS";

    private String returnMsg;

    private boolean signValid = false;

    //公众账号ID, 调用接口提交的公众账号ID
    private String appId;

    private String mchId;

    private String deviceInfo;

    //业务结果
    private String resultCode = "FAIL";  //"SUCCESS";

    //错误码
    private String errCode;

    //错误描述
    private String errCodeDes;

    public Map<Object, Object> initial(Map<String, String> params, String key) {
        SortedMap<Object, Object> validParams = new TreeMap<>();
        try {
            params.keySet().forEach(x -> {
                String value = params.get(x) != null ? params.get(x).trim() : null;
                validParams.put(x, value);
            });

            if (key == null || "".equals(key.trim())) {
                key = WxPayConfig.getInstance().getKey();
            }
            setSignValid(PayCommonUtil.isTenpaySign("UTF-8", validParams, key));
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            setReturnCode((String) validParams.get("return_code"));
            setReturnMsg("微信支付平台返回：" + validParams.get("return_msg"));
        }

        try {
            if ("SUCCESS".equals(getReturnCode())) {
                setAppId((String) validParams.get("app_id"));
                setMchId((String) validParams.get("mch_id"));
                setDeviceInfo((String) validParams.get("device_info"));

                setResultCode((String) validParams.get("result_code"));
                setErrCode((String) validParams.get("err_code"));
                setErrCodeDes((String) validParams.get("err_code_des"));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return validParams;
    }

}
